package cn.edu.zjicm.wordsnet_d.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Locale;

import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.data.OneWord;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.os.PowerManager;
import android.text.Spannable;
import android.text.style.ForegroundColorSpan;
import android.view.Display;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class Utils {
	/**
	 * 将TextView中的str文本以color色进行高亮, 注意TextView中必须使用BufferType.SPANNABLE 对比时忽略大小写
	 * 
	 * @param textView
	 * @param str
	 *            欲高亮的文字
	 * @param color
	 *            高亮颜色
	 */
	public static void hightLisht(TextView textView, String str, int color) {
		if (textView != null && str != null && textView.getText() instanceof Spannable) {
			Spannable span = (Spannable) textView.getText();
			int start = 0;
			while (true) {
				start = textView.getText().toString().toLowerCase(Locale.getDefault()).indexOf(str.toLowerCase(Locale.getDefault()), start);
				if (start == -1)
					return;
				span.setSpan(new ForegroundColorSpan(color), start, start + str.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				start = start + str.length();
			}
		}
	}

	/**
	 * 将dip转px
	 * 
	 * @param mContext
	 * @param dip
	 * @return
	 */
	public static int changeDipToPx(Context mContext, int dip) {
		float scale = mContext.getResources().getDisplayMetrics().density;
		int px = (int) (dip * scale + 0.5f);
		return px;
	}

	/**
	 * 将TextView中的字符全角化，避免自动换行
	 * 
	 * @param input
	 * @return
	 */
	public static String ToDBC(String input) {
		char[] c = input.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == 12288) {
				c[i] = (char) 32;
				continue;
			}
			if (c[i] > 65280 && c[i] < 65375)
				c[i] = (char) (c[i] - 65248);
		}
		return new String(c);
	}

	public static Bitmap getbitmap(String imageUri) {
		// 显示网络上的图片
		Bitmap bitmap = null;
		try {
			URL myFileUrl = new URL(imageUri);
			HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(is);
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return bitmap;
	}

	public static Bitmap getBitmapFromView(View view, Context context) {
		LayoutParams lp = new LayoutParams(getScreenWidth(context), getScreenHeight(context));
		view.setLayoutParams(lp);
		view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
		Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmap);
		view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
		view.draw(canvas);
		return bitmap;
	}

	private static int screenWidth;

	@SuppressLint("NewApi")
	public static int getScreenWidth(Context context) {
		if (screenWidth == 0) {
			Display display = ((Activity) context).getWindowManager().getDefaultDisplay();
			// android3.2以前获取屏幕宽度用display.getWidth()取得，android3.2以后Google推荐用getSize()方法获得。
			if (getCurrentVersion() >= 13) {
				Point size = new Point();
				display.getSize(size);
				screenWidth = size.x;
				screenHeight = size.y;
			} else {
				screenWidth = display.getWidth();
				screenHeight = display.getHeight();
			}
		}
		return screenWidth;
	}

	private static int screenHeight;

	@SuppressLint("NewApi")
	public static int getScreenHeight(Context context) {
		if (screenHeight == 0) {
			Display display = ((Activity) context).getWindowManager().getDefaultDisplay();
			// android3.2以前获取屏幕宽度用display.getWidth()取得，android3.2以后Google推荐用getSize()方法获得。
			if (getCurrentVersion() >= 13) {
				Point size = new Point();
				display.getSize(size);
				screenWidth = size.x;
				screenHeight = size.y;
			} else {
				screenWidth = display.getWidth();
				screenHeight = display.getHeight();
			}
		}
		return screenHeight;
	}

	public static int getCurrentVersion() {
		return android.os.Build.VERSION.SDK_INT;
	}

	// 如果要注释掉小米沉浸式状态栏，只需要注释掉本代码中内容并返回false
	public static boolean immersionStatusBarForXiaoMi(Activity activity) {
		boolean flag = false;
		Window window = activity.getWindow();
		Class clazz = window.getClass();
		try {
			int tranceFlag = 0;
			int darkModeFlag = 0;
			Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");

			Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_TRANSPARENT");
			tranceFlag = field.getInt(layoutParams);

			field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
			darkModeFlag = field.getInt(layoutParams);

			Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
			// 只需要状态栏透明
			// extraFlagField.invoke(window, tranceFlag, tranceFlag);
			// 或
			// 状态栏透明且黑色字体
			extraFlagField.invoke(window, tranceFlag | darkModeFlag, tranceFlag | darkModeFlag);
			// 清除黑色字体
			extraFlagField.invoke(window, 0, darkModeFlag);
			flag = true;
		} catch (Exception e) {
			flag = false;
			// e.printStackTrace();
		}
		return flag;
	}

	public static String changeCharsetToUTF8(String str) {
		if (str != null) {
			byte[] bs = str.getBytes();
			try {
				return new String(bs, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	// 设置为列表底部
	public static void setListItemBottom(RelativeLayout ll, TextView divider) {
		if (NightModeUtil.isNightModeNow())
			ll.setBackgroundResource(R.drawable.rectangle_half_bottom);
		else
			ll.setBackgroundResource(R.drawable.setting_background_bottom_selector);
		divider.setVisibility(View.GONE);
	}

	public static void setListItemSingle(RelativeLayout ll, TextView divider) {
		if (NightModeUtil.isNightModeNow())
			ll.setBackgroundResource(R.drawable.rectangle_normal);
		else
			ll.setBackgroundResource(R.drawable.setting_background_selector);
		divider.setVisibility(View.GONE);
	}

	// 设置为列表顶部
	public static void setListItemTop(RelativeLayout ll) {
		if (NightModeUtil.isNightModeNow())
			ll.setBackgroundResource(R.drawable.rectangle_half_top);
		else
			ll.setBackgroundResource(R.drawable.setting_background_top_selector);
	}

	public static enum shareWay {
		wechat, wechatTimeline, QQ, QZone, weibo
	};

	public static enum shareFrom {
		mainActivity, slideMenu, afterPunchOut, leardboardtab1, leardboardtab2, leardboardtab3
	}

	public static enum createBitmapMode {
		forPunchout, forMainActivity
	}

	public static enum welcomeADsIndex {
		ad1, ad2, ad3, adPro
	}

	/**
	 * 得到屏幕状态
	 * 
	 * @param mContext
	 * @return false表示锁屏
	 */
	public static boolean getScreenState(Context mContext) {
		PowerManager manager = (PowerManager) mContext.getSystemService(Activity.POWER_SERVICE);
		return manager.isScreenOn();
	}

}
